import Viewer from 'bpmn-js/lib/Viewer';


// 网格背景
import GridLineModule from 'diagram-js-grid-bg'
import ZoomScrollModule from 'diagram-js/lib/navigation/zoomscroll'
import MoveCanvasModule from 'diagram-js/lib/navigation/movecanvas'
import React, {useEffect, useRef, useState} from 'react';

// 国际化-目前是汉化
import translate from "@/components/properties-panel-extension/modules/Translate";
import {getProcessDefinition} from "@/clientApi/flowable/definition";
import {Button, Tooltip} from "antd";
import {DragOutlined, ZoomInOutlined, ZoomOutOutlined} from "@ant-design/icons";


import  "./index.css"

// 定义配置选项的类型
interface ModelerOptions {
    [key: string]: any;
}

interface MyComponentProps {
    processKeys?: string|null;
    formObject?: string;
}

// 查看流程图单独摘出图
const processView: React.FC<MyComponentProps> = (props: any) => {


    const [key, setKey] = useState(props?.processKeys || '');
    const [formObject, setFormObject] = useState(JSON.parse(props?.formObject||null) || {});


    const modelerRef = useRef(null);
    const bpmnModeler = useRef<Viewer|null>(null);
// 修改 modeler 配置
    // 初始化模型器配置
    const options: ModelerOptions = {

        gridLine: {
            smallGridSpacing: 20,
            gridSpacing: 80,
            gridLineStroke: 0.5,
            gridLineOpacity: 0.6,
            gridLineColor: '#ccc',
        }
    };
    // 初始化 bpmn-js 模型器
    const initializeModeler = () => {
        if (!modelerRef.current) return;

        bpmnModeler.current = new Viewer({
            container: modelerRef.current,
            additionalModules: [
                translate,
                GridLineModule,
                ZoomScrollModule,
                MoveCanvasModule
            ],
            ...options
        });


    };

    // 加载流程定义数据
    const loadProcessDefinition = async (key:string) => {
        try {
            const res:any = await getProcessDefinition(key);
            if (res?.code === 200) {
                await bpmnModeler.current?.importXML(res.data);
                console.log('Diagram imported successfully');
            } else {
                console.error('Failed to fetch process definition:', res);
            }
        } catch (err) {
            console.error('Error fetching or importing process definition:', err);
        }
    };

    // 加载默认的初始 XML 数据
    const loadDefaultDiagram = async () => {
        try {
            console.log("props.xmlData", formObject);
            await bpmnModeler.current?.importXML(formObject.xmlData);
            console.log('Default diagram imported successfully');
            // 流程线高亮设置
            if (formObject.nodeData !== undefined && formObject.nodeData.length > 0) {
              await  fillColor(formObject.nodeData);
            }
        } catch (err) {
            console.error('Error importing default diagram:', err);
        }
    };

    // 放大
    const zoomIn = () => {
        if (bpmnModeler.current) {
            const canvas:any = bpmnModeler.current.get('canvas');
            const currentZoom = canvas.zoom();
            canvas.zoom(currentZoom + 0.1);
        }
    };

    // 缩小
    const zoomOut = () => {
        if (bpmnModeler.current) {
            const canvas:any = bpmnModeler.current.get('canvas');
            const currentZoom = canvas.zoom();
            canvas.zoom(currentZoom - 0.1);
        }
    };

    // 居中
    const centerView = () => {
        if (bpmnModeler.current) {
            const canvas:any = bpmnModeler.current.get('canvas')
            canvas.zoom("fit-viewport", "auto");
        }
    };

    // 设置高亮颜色的
    const fillColor = async  (nodeData: any) => {
        const canvas:any = bpmnModeler.current?.get('canvas')
        console.log("bpmnModeler.current.get",canvas)
        bpmnModeler.current?.getDefinitions().rootElements[0].flowElements.forEach((n:any) => {
            // console.log("nodeData", canvas)
            const completeTask = nodeData.find((m:any) => m.key === n.id)
            // console.log("completeTask", completeTask)
            const todoTask = nodeData.find((m:any) => !m.completed)
            const endTask = nodeData[nodeData.length - 1]
            if (n.$type === 'bpmn:UserTask') {
                if (completeTask) {
                    canvas.addMarker(n.id, completeTask.completed ? "highlight" : "highlight-todo")
                    n.outgoing?.forEach((nn:any) => {
                        const targetTask = nodeData.find((m:any) => m.key === nn.targetRef.id)
                        if (targetTask) {
                            if (todoTask && completeTask.key === todoTask.key && !todoTask.completed) {
                                canvas.addMarker(nn.id, todoTask.completed ? 'highlight' : 'highlight-todo')
                                canvas.addMarker(nn.targetRef.id, todoTask.completed ? 'highlight' : 'highlight-todo')
                            } else {
                                canvas.addMarker(nn.id, targetTask.completed ? 'highlight' : 'highlight-todo')
                                canvas.addMarker(nn.targetRef.id, targetTask.completed ? 'highlight' : 'highlight-todo')
                            }
                        }
                    })
                }
            }
            // 排他网关
            else if (n.$type === 'bpmn:ExclusiveGateway') {
                if (completeTask) {
                    canvas.addMarker(n.id, completeTask.completed ? 'highlight' : 'highlight-todo')
                    n.outgoing?.forEach((nn:any) => {
                        const targetTask = nodeData.find((m:any) => m.key === nn.targetRef.id)
                        if (targetTask) {

                            canvas.addMarker(nn.id, targetTask.completed ? 'highlight' : 'highlight-todo')
                            canvas.addMarker(nn.targetRef.id, targetTask.completed ? 'highlight' : 'highlight-todo')
                        }
                    })
                }
            }
            // 并行网关
            else if (n.$type === 'bpmn:ParallelGateway') {
                if (completeTask) {
                    canvas.addMarker(n.id, completeTask.completed ? 'highlight' : 'highlight-todo')
                    n.outgoing?.forEach((nn:any) => {
                        const targetTask = nodeData.find((m:any) => m.key === nn.targetRef.id)
                        if (targetTask) {
                            canvas.addMarker(nn.id, targetTask.completed ? 'highlight' : 'highlight-todo')
                            canvas.addMarker(nn.targetRef.id, targetTask.completed ? 'highlight' : 'highlight-todo')
                        }
                    })
                }
            } else if (n.$type === 'bpmn:StartEvent') {
                n.outgoing.forEach((nn:any) => {
                    const completeTask = nodeData.find((m:any) => m.key === nn.targetRef.id)
                    if (completeTask) {
                        canvas.addMarker(nn.id, 'highlight')
                        canvas.addMarker(n.id, 'highlight')
                        return;
                    }
                })
            } else if (n.$type === 'bpmn:EndEvent') {
                if (endTask.key === n.id && endTask.completed) {
                    canvas.addMarker(n.id, 'highlight')
                    return;
                }
            }
        })
    }
    useEffect(() => {
        initializeModeler();
        if (key) {
            loadProcessDefinition(key).then(r => console.log(r));
        } else {
            loadDefaultDiagram().then(r => console.log(r));
        }
        return () => {
            if (bpmnModeler.current) {
                bpmnModeler.current.destroy();
            }
        };
    }, [key, formObject]);

    return (
        <>
            <div
                ref={modelerRef}
                style={{
                    width: '100%',
                    height: "65vh",
                    backgroundColor: '#ffffff',
                }}
            />
            <div style={{
                position: "absolute",
                right: "10%",
                top: "15%"
            }}>
                <Tooltip
                    placement="bottom"
                    title="放大"
                    style={{fontSize: 12}}
                >
                    <Button icon={<ZoomOutOutlined/>} size={"small"} onClick={zoomIn}/>
                </Tooltip><Tooltip
                placement="bottom"
                title="缩小"
                style={{fontSize: 12}}
            >
                <Button icon={<ZoomInOutlined/>} style={{marginLeft: "10px"}} size={"small"} onClick={zoomOut}/>
            </Tooltip><Tooltip
                placement="bottom"
                title="居中"
                style={{fontSize: 12}}
            >
                <Button icon={<DragOutlined/>} style={{marginLeft: "10px"}} size={"small"} onClick={centerView}/>
            </Tooltip>
            </div>
        </>
    );
};

export default processView;
